package cn.edu.ctbu.lab.api;

import cn.edu.ctbu.lab.domain.Score;
import cn.edu.ctbu.lab.helper.RUtil;
import cn.edu.ctbu.lab.service.ScoreService;
import cn.edu.ctbu.lab.service.ScoreService;
import cn.edu.ctbu.lab.vo.BTPageDO;
import cn.edu.ctbu.lab.vo.ScoreExt;
import cn.edu.ctbu.lab.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@Slf4j
public class ScoreRestController {

    @Autowired
    private ScoreService scoreService;

    /**
     * 基本分页
     * @param offset
     * @param limit
     * @return*/
     
    @RequestMapping(value = "/api/score/list")
    public BTPageDO<ScoreExt> list(int courseId,int offset, int limit){

        int pageIndex=offset/limit;


        int pageSize=limit;

        BTPageDO<ScoreExt> myList=scoreService.findByPage(courseId,pageIndex,pageSize);



        return myList;


    }


    @GetMapping("/api/score/read")
    public R read(Integer id){
        Score score= scoreService.findById(id).get();

        return RUtil.success(score);

    }


    @PostMapping(value = "/api/score/add")
    public R add(@Valid Score score, BindingResult bindingResult){

        if(bindingResult.hasErrors()){
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return RUtil.error(-2,
                    "出错了!"+bindingResult.getFieldError().getDefaultMessage());
        }
        scoreService.add(score);

        return RUtil.success();

    }


    @PutMapping(value = "/api/score/update")
    public R update(@Valid Score score, BindingResult bindingResult){

        if(bindingResult.hasErrors()){
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return RUtil.error(-2,
                    "出错了!"+bindingResult.getFieldError().getDefaultMessage());
        }


        scoreService.update(score);

        return RUtil.success();

    }


    @DeleteMapping(value = "/api/score/delete")
    public R delete(Integer[] ids){

        Integer mylen= ids.length;
        for (int i = 0; i <mylen ; i++) {

            //读取数据,再删除
            //Score item = scoreService.findById(ids[i]).get();

            scoreService.delete(ids[i]);


        }

        return RUtil.success();

    }


}